package com.googlecode.serialization;

public class IntegerTranscoder extends AbsPrimitiveTypeTranscoder<Integer> {

	@Override
	public Integer decode(DataInfo d) {
		if (this.primitiveAsString) {
			byte[] data = d.getData();
			if ((d.getFlag() & SerializingTranscoder.COMPRESSED) != 0) {
				data = uncompress(d.getData());
			}
			return  (d.getFlag() == 0) ?  Integer.valueOf(decodeString(data)) : null;
		} else {
			return (SerializingTranscoder.SPECIAL_INT == d.getFlag()) ?
				 this.transcoderHelper.decodeInt(d.getData()): null;
		}
	}

	@Override
	public DataInfo encode(Integer l) {
		/**
		 * store integer as string
		 */
		if (this.primitiveAsString) {
			byte[] b = encodeString(l.toString());
			int flags = 0;
			if (b.length > this.compressionThreshold) {
				byte[] compressed = compress(b);
				if (compressed.length < b.length) {
					if (logger.isDebugEnabled()) {
						logger.debug(String.format("Compressed %s from %d to %d" , l.getClass().getName(), b.length, compressed.length));
					}
					b = compressed;
					flags |= SerializingTranscoder.COMPRESSED;
				} else {
					if (logger.isDebugEnabled()) {
						logger.debug(String.format("Compression increased the size of %s from %d to %d", l.getClass().getName() , b.length,compressed.length));
					}
				}
			}
			return new DataInfo(flags, b, b.length, -1);
		}
		return new DataInfo(SerializingTranscoder.SPECIAL_INT, this.transcoderHelper.encodeInt(l));
	}

}
